#include "HeadFile.h"
#include "DHT11.h"
#include "Time.h"

int32_t PD3_VolCheck(void)//检测PD3口高低电平函数
{
	if(GPIOPinRead(GPIO_PORTD_BASE,GPIO_PIN_3)==GPIO_PIN_3)
	{
		return 1;
	}
	
	if(GPIOPinRead(GPIO_PORTD_BASE,GPIO_PIN_3)==0)
	{
		return 0;
	}
	
	return -1;
}


void DHT11_Res(void)//DHT11初始化
{
	GPIOPinTypeGPIOOutput(GPIO_PORTD_BASE,GPIO_PIN_3);
	GPIOPinWrite(GPIO_PORTD_BASE,GPIO_PIN_3,0);//主机拉低总线
	delay(20);
	GPIOPinWrite(GPIO_PORTD_BASE,GPIO_PIN_3,GPIO_PIN_3);
	delayMicroseconds(30);
}

uint8 DHT11_Check(void)//检测从机是否有响应
{
	uint8 t = 0;
	GPIOPinTypeGPIOInput(GPIO_PORTD_BASE,GPIO_PIN_3);
	while(PD3_VolCheck())//等待从机拉低总线
	{
		t++;
		delayMicroseconds(1);
		if(t > 100)return 1;//若长时间未响应则报错1
	}
	
	t = 0;
	
	while(!(PD3_VolCheck()))
	{
		t++;
		delayMicroseconds(1);
		if(t > 100)return 2;//低电平响应超时报错2
	}
	return 0;//正常则返回0
}

uint8 DHT11_Read_Bit(void)//读取一个位
{
 	uint8 retry=0;
	while(PD3_VolCheck()&&retry<100)//等待低电平
	{
		retry++;
		delayMicroseconds(1);
	}
	retry=0;
	while(!PD3_VolCheck()&&retry<100)//等待高电平
	{
		retry++;
		delayMicroseconds(1);
	}
	delayMicroseconds(40);;//等待40us
	if(PD3_VolCheck())return 1;
	else return 0;		   
}

uint8 DHT11_Read_Byte(void)    //读取一个字节
{        
    uint8 i,dat;
    dat=0;
	for (i=0;i<8;i++) 
	{
   		dat<<=1; 
	    dat|=DHT11_Read_Bit();
    }						    
    return dat;
}


uint8 DHT11_Read_Data(uint8 *tempH,uint8 *tempL,uint8 *humiH,uint8 *humiL)//读取数据
{
	uint8 buf[5];
	DHT11_Res();
	if(DHT11_Check() == 0)
	{
		buf[0] = DHT11_Read_Byte();//湿度高8位
		buf[1] = DHT11_Read_Byte();//湿度低8位
		buf[2] = DHT11_Read_Byte();//温度高8位
		buf[3] = DHT11_Read_Byte();//温度低8位
		buf[4] = DHT11_Read_Byte();//接收校验位

		delayMicroseconds(40);
		if((buf[0]+buf[1]+buf[2]+buf[3]) == buf[4])//校验正确
		{
			*humiH = buf[0];
			*humiL = buf[1];
			*tempH = buf[2];
			*tempL = buf[3];
		}
		
		else
		{
			return 1;//校验不通过则报错
		}
	}
	
	else
	{
		return 2;//电平初始化失败，则报错2
	}
	
	return 0;
}



